var topMenus
var topPages = {};
var rightPages = {};
var topName = '';
var pageTab;
var topPage;

function ajax(url,method,data){
    method = method || 'GET';
    data = data||{};
    return new Promise((r,j)=>{
        var aj = new XMLHttpRequest;
        aj.onreadystatechange = function(){
            if (aj.readyState === 4) {
                if(aj.status === 200){
                    try{
                        var data = JSON.parse(aj.responseText);
                        if(data.error) throw data.msg;
                        r(data)
                    }catch(e){
                        j(e);
                    }
                }else{
                    j('网络错误')
                }
            }
        }
        aj.open(method,url,true);
        aj.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
        aj.setRequestHeader('AJAX',1);
        var postData = [];
        for (const key in data) {
            const val = data[key];
            postData.push(key+'='+encodeURIComponent(val));
        }
        aj.send(postData.join('&'));
    })
}

var scriptInitFuns = {};

function regInitFun(id,func){
    scriptInitFuns[id] = func
}

HTMLDivElement.prototype.getPage = function(url,header,callback){
    var aj = new XMLHttpRequest;
    var _this = this;
    aj.onreadystatechange = function(){
        if (aj.readyState === 4 && aj.status === 200) {
            _this.innerHTML = aj.responseText;
            var scripts = _this.getElementsByTagName('script');
            var head = document.getElementsByTagName('head')[0];
            for (var i = 0; i < scripts.length; i++) {
                var script = scripts[i];
                var id = script.id;
                if(!head.querySelector('#'+id)){
                    var newScript = document.createElement('script');
                    newScript.id = id;
                    if (script.src) {
                        newScript.src = script.src;
                    } else {
                        newScript.innerHTML = script.innerHTML;
                    }
                    head.appendChild(newScript);
                }
                scriptInitFuns[id]();
            }
            if(callback){
                callback(_this);
            }
          }
    }
    aj.open('GET',url,true)
    aj.setRequestHeader('AJAX',1)
    if(header){
        for (const key in header) {
            aj.setRequestHeader(key,header[key])
        }
    }
    aj.send();
}


HTMLDivElement.prototype.showModal = function(){
    this.style.display = 'block';
    var width = this.offsetWidth;
    this.style.marginLeft = (-width/2)+'px';
}
HTMLDivElement.prototype.hide = function(){
    this.style.display = 'none';
}

HTMLDivElement.prototype.indexOf = function(){
    var elms = this.parentNode.querySelectorAll('.'+Array.from(this.classList).join('.'));
    return indexOf(elms,this);
}

function indexOf(elms,elm){
    for(let i=0;len=elms.length,i<len;i++){
        if(elms[i]==elm){
            return i;
        }
    }
    return -1;
}

function switchPageTab(leftMenus,cur){
    leftMenus.forEach(o=>{
        var page = o.querySelector('a').dataset.page
        if(cur!=null && page==cur.dataset.name){
            o.classList.add('active');
        }else{
            o.classList.remove('active');
        }
    })
}


//绑定表格的排序事件
var sortFunList = {};
function bindSort(selector,sortFun){
    sortFunList[pageTab.dataset.name] = {
        'selector':selector,
        'pageTab':pageTab,
        'fun':sortFun
    }
}

function route(){
    var hash = window.location.hash.substring(1);
    if(!hash || hash=="/") hash = "/index";
    var origin = window.location.origin;
    var path = window.location.pathname;
    document.getElementById('right-page').getPage(origin+path+hash);
}

function addNewMember(ev){
    var tr = ev.target.parentNode.parentNode;
    var newTr = tr.cloneNode(true);
    newTr.querySelectorAll('input').forEach(inp=>{
        inp.dataset.name = inp.name;
        inp.name = '';
        switch(inp.type){
            case 'radio':
                break;
            default:
                inp.value = "";
        }
    })
    tr.after(newTr)
    rename(tr.parentNode);
    return newTr;
}
var clear = function(tbody){
    tbody.querySelectorAll('input').forEach(inp=>{
        inp.dataset.name = inp.name;
        inp.name = '';
    })
}
var rename = function(tbody){
    var reg = /([a-zA-Z]+)\[(\d+)\]/
    var trs = Array.from(tbody.querySelectorAll('.tr')).reverse();
    var len = trs.length;
    trs.forEach((tr,index)=>{
        tr.querySelectorAll('input').forEach(inp=>{
            var names = inp.name||inp.dataset.name;
            var matches = names.match(reg);
            inp.name = matches[1]+'['+(len-1-index)+']'
            if(inp.dataset.name) delete(inp.dataset.name)
        })
        tr.querySelector('.td').innerText = len-index;
    })
}

function onAddMemberInputKeyDown(ev){
    if(ev.key=='Enter'){
        ev.preventDefault();
        var tr = addNewMember(ev)
        tr.querySelector('.td:nth-child(2) input').focus();
    }
}

document.addEventListener('DOMContentLoaded',()=>{
    var leftMenus = document.querySelectorAll('.left-menu .menus li');
    var active = function(){
        var path = window.location.pathname;
        var hash = window.location.hash;
        var index = hash.indexOf('?');
        var fullPath;
        if(index>-1){
            fullPath = path+hash.substring(0,index);
        }else{
            fullPath = path+hash;
        }
        for (const li of leftMenus) {
            var href = li.dataset.path;
            if(href==fullPath){
                li.classList.add('active');
            }else{
                li.classList.remove('active');
            }
        }
    }
    window.onhashchange = function(ev){
        active();
        route();
    }

    
    active();
    route();
    leftMenus.forEach(li=>{
        li.addEventListener('click',ev=>{
            leftMenus.forEach(o=>{
                o.classList.remove('active')
            })
            li.classList.add('active');
        })
    });

    document.addEventListener('click',ev=>{
        switch(true){
            case ev.target.matches('.modal .icon-close'):
                ev.target.parentNode.style.display = 'none';
                break;
            
            case ev.target.matches('.search-result-box'):
                ev.target.relInput.focus();
            case ev.target.matches('.search-box .input input'):
            case ev.target.matches('.search-box .input span'):
                break;
            case ev.target.matches('.search-result-box ul li'):
            case ev.target.matches('.search-result-box ul li span'):
                var item = ev.target;
                if(ev.target.matches('.search-result-box ul li span')){
                    item = ev.target.parentNode;
                }
                var text = item.innerText;
                var parentNode = item.parentNode.parentNode;
                var relInput = parentNode.relInput;
                var i = text.lastIndexOf('(');
                text = text.substring(0,i);
                var id = item.dataset.id;
                relInput.value = text;
                relInput.dataset.valId = id;
                relInput.dataset.val = text;
                parentNode.hide();
                break;
            case ev.target.matches('#add-member .list-table .btns .icon-jia'):
                addNewMember(ev)
                break;
            case ev.target.matches('#add-member .list-table .btns .icon-jian'):
                var tr = ev.target.parentNode.parentNode;
                var parent = tr.parentNode;
                if(parent.querySelectorAll('.tr').length==1){
                    tr.querySelectorAll('input').forEach(inp=>{
                        if(inp.type!='checkbox'){
                            inp.value = '';
                        }
                    })
                    return;
                }
                clear(parent);
                parent.removeChild(tr);
                rename(parent);
                break;
            default:
                document.querySelectorAll('.search-result-box').forEach(o=>{
                    o.relInput.value = o.relInput.dataset.val || "";
                    o.hide();
                })
                break;
        }
    })

    window.onmousewheel= function(ev){
        document.querySelectorAll('.search-result-box').forEach(o=>{
            o.relInput.value = o.relInput.dataset.val || "";
            o.style.display = 'none'
        })
    }
})

function submitForm(ev){
    ev.preventDefault();
    var data = {};
    for (const name in ev.target.form.elements) {
        if (Object.hasOwnProperty.call(ev.target.form.elements, name)) {
            const element = ev.target.form.elements[name];
            if(isNaN(name)){
                var val = element.dataset.id || element.value;
                if(element.required && val===""){
                    alert('请填写'+element.parentNode.parentNode.querySelector('.label').innerText)
                    return;
                }
                data[name] = element.value;
            }
        }
    }
    ajax(ev.target.form.action,'post',data).then(resp=>{
        //如果是modal
        if(ev.target.form.parentNode.classList.contains('modal')){
            ev.target.form.parentNode.hide()
        }
        alert('操作成功');
        route();
    }).catch(e=>{
        alert(e);
    })
}

function showSearchResultBox(searchResultBox,elm){
    var pos = elm.getBoundingClientRect();
    searchResultBox.style.top = (pos.top + pos.height)+'px';
    searchResultBox.style.width = pos.width-2+'px';
    searchResultBox.style.left = pos.left+'px';
    searchResultBox.style.display = 'block';
}

function searchAndShowResultBox(inputElm,urlPath){
    var resultBox = inputElm.resultBox;
    if(!resultBox){
        resultBox = document.createElement('div');
        resultBox.className = 'search-result-box';
        resultBox.relInput = inputElm;
        document.body.appendChild(resultBox);
        inputElm.resultBox = resultBox;
    }
    if(inputElm.timer){
        clearTimeout(inputElm.timer)
    }
    inputElm.timer = setTimeout(() => {
        resultBox.innerHTML = `<div class="empty">加载中</div>`
        resultBox.getPage(urlPath+'?keyword='+inputElm.value)
    }, 400);
    showSearchResultBox(resultBox,inputElm);
}

function searchBoxOnInput(ev,urlPath){
    if(ev.type=='keydown'){
        if(ev.key && ev.key=="Enter"){
            ev.preventDefault();
        }
    }
    searchAndShowResultBox(ev.target,urlPath)
}

function _showSearchResultBox(ev){
    if(ev.target.resultBox){
        showSearchResultBox(ev.target.resultBox,ev.target)
    }
}

function _searchBoxOnInput(ev,urlPath){
    var input = ev.target.parentNode.querySelector('input');
    input.focus();
    searchAndShowResultBox(input,urlPath)
}

function addMember(ev){
    ev.preventDefault();
    var data = {"parentId":0,"members":[]};
    for (const name in ev.target.form.elements) {
        const element = ev.target.form.elements[name];
        if(isNaN(name)){
            var val = (element.dataset ? element.dataset.id : null) || element.value;
            if(element.required && val===""){
                alert('姓名必填，请填写完整')
                return;
            }
            var matches = name.match(/([a-zA-Z]+)\[(\d+)\]/);
            if(matches && matches.length==3){
                var dn = matches[1];
                var idx = matches[2];
                if(!data.members[idx]) data.members[idx] = {};
                data.members[idx][dn] = element.value;
            }
        }
    }
    data.parentId = ev.target.form.father.dataset.valId;
    if(data.parentId==""){
        alert('请填写父亲');
        return;
    }
    ajax(ev.target.form.action,'post',{"data":JSON.stringify(data)}).then(resp=>{
        //如果是modal
        if(ev.target.form.parentNode.classList.contains('modal')){
            ev.target.form.parentNode.hide()
        }
        alert('新增成员成功');
        route();
    }).catch(e=>{
        alert(e);
    })
}

function editMember(tr){
    var fieldMap = ['id','name','sex','birth','parent_id','spouse', 'address', 'phone','sort', 'remark']
    var modal = document.getElementById('edit-member');
    var vals = {};
    tr.querySelectorAll('.td').forEach((td,index)=>{
        var val = td.innerText;
        var field = fieldMap[index];
        if(!field) return;
        vals[field] = val;
        if(field=='sex'){
            if(val!='未知'){
                vals[field] = {"男":"1","女":"2"}[val]
            }else{
                vals[field] = '1'
            }
        }
        if(field=='parent_id'){
            vals[field] = td.dataset.parentId;
            vals['parent_name'] = val;
        }
    })
    modal.showModal();
    modal.dataset.id = tr.dataset.id;
    var form = modal.querySelector('form');
    for (const key in vals) {
        switch(key){
            case 'id':
                form.elements.id.value = tr.dataset.id;
                break;
            case 'parent_name':
                break;
            case 'sex':
                form.elements.sex.forEach(elm=>{
                    if(elm.value==vals['sex']){
                        elm.checked = true;
                    }
                })
                break;
            case 'parent_id':
                form.elements[key].value = vals['parent_name']
                form.elements[key].dataset.val = vals['parent_name']
                form.elements[key].dataset.valId = vals['parent_id'];
                break;
            default:
                form.elements[key].value = vals[key]
        }
    }
}

function submitEditMember(ev){
    ev.preventDefault();
    var form = ev.target.parentNode.parentNode;
    if(form.name.value==""){
        alert('请填写姓名')
        return;
    }
    if(form.parent_id.value==""){
        alert("请选择父亲");
        return;
    }
    var data = {};
    for (const name in form.elements) {
        const element = form.elements[name];
        if(isNaN(name)){
            switch(name){
                case 'parent_id':
                    data[name] = element.dataset.valId;
                    break;
                default:
                    data[name] = element.value;
            }
        }
    }
    ajax(form.action,'post',data).then(resp=>{
        alert('操作成功');
        form.parentNode.hide();
        route();
    }).catch(e=>{
        alert(e);
    })
}

function delMember(tr){
    if(!confirm('确认删除吗?')){
        return;
    }
    var id = tr.dataset.id;
    ajax('/admin/members/delete','post',{id}).then(()=>{
        route();
    }).catch(e=>{
        alert(e);
    })
}